package cn.edu.lingnan.service.impl;

import cn.edu.lingnan.mapper.TaskMapper;
import cn.edu.lingnan.service.ExamService;
import cn.edu.lingnan.service.TaskService;
import cn.edu.lingnan.user.pojos.Exam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private ExamService examService;


    @Override
    @Transactional
    public void publishExams() {
        LocalDateTime now = LocalDateTime.now();
        List<Exam> examsToPublish = taskMapper.findPublishedExams(now);
        if (examsToPublish != null && !examsToPublish.isEmpty()) {
            List<Integer> examIds = examsToPublish.stream()
                    .map(Exam::getExamId)
                    .collect(Collectors.toList());
            int updatedRows = taskMapper.updateStatusToOngoing(examIds);
            System.out.println("已发布考试数量: " + updatedRows);
        }
    }

    /**
     * 将状态从“考试中” (2) 更新为“已结束” (3)
     */
    @Override
    @Transactional
    public void endExams() {
        LocalDateTime now = LocalDateTime.now();
        List<Exam> examsToEnd = taskMapper.findOngoingExams(now);
        if (examsToEnd != null && !examsToEnd.isEmpty()) {
            List<Integer> examIds = examsToEnd.stream()
                    .map(Exam::getExamId)
                    .collect(Collectors.toList());
            int updatedRows = taskMapper.updateStatusToEnded(examIds);
            System.out.println("已结束考试数量: " + updatedRows);
        }
    }



}
